import React, { useState, useEffect } from "react";

import { Input, DatePicker, Select, Button, Table } from "antd";
import { useSearchParams } from "react-router-dom";
import moment from "moment";
import ExportJsonExcel from "js-export-excel";
import { OrderInquiry } from "../../serve";
import "./order.scss";
const { RangePicker } = DatePicker;
// const { Option } = Select;

/**
 *
 * @returns  订单查询
 */

const Order = () => {
  const [oderData, setOrderData] = useState([]);
  const [serchData, setSerchData] = useState({
    page: 1,
    limit: 11,
  });
  const [searchParams, setSearchParams] = useSearchParams();
  let nvrId = searchParams.get("nvrId");
  const [total, setTotal] = useState(0);
  function disabledDate(current) {
    return current && current > moment().endOf("day");
  }
  // function eqTypeChange(val) {
  //   console.log("设备类型" + val);
  // }
  let timers = null;

  useEffect(() => {
    if (nvrId) {
      OrderInquiry({ ...serchData, nvrSerialnumber: nvrId }).then((res) => {
        setOrderData(res.data);
        setTotal(res.count);
      });
      setSearchParams({});
      nvrId = null;
    } else {
      OrderInquiry(serchData).then((res) => {
        setOrderData(res.data);
        setTotal(res.count);
      });
    }
  }, [serchData]);
  let inputWidth = "65%";

  const downloadExcel = () => {
    var option = {};
    let dataTable = [];

    oderData.forEach((item) => {
      let obj = {
        tradeNo: item.tradeNo,
        nvrSerialNumber: item.orderInformation.nvrSerialNumber,
        notifyTime: item.notifyTime,
        nvrStartTime: moment(item.orderInformation.nvrStartTime).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        nvrEndTime: moment(item.orderInformation.nvrEndTime).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        buyerPayAmount: `￥${item.buyerPayAmount}`,
        orderSettleAccounts: `￥${item.orderInformation.orderSettleAccounts}`,
      };
      dataTable.push(obj);
    });
    option.fileName = "订单管理";
    option.datas = [
      {
        sheetData: dataTable,
        sheetName: "sheet",
        sheetFilter: [
          "tradeNo",
          "nvrSerialNumber",
          "notifyTime",
          "nvrStartTime",
          "nvrEndTime",
          "buyerPayAmount",
          "orderSettleAccounts",
        ],
        sheetHeader: [
          "订单号",
          "设备ID",
          "付款时间",
          "授权开始时间",
          "授权结束时间",
          "支付金额",
          "订单金额",
        ],
      },
    ];

    var toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  };

  const columns = [
    {
      title: "订单号",
      dataIndex: "tradeNo",
    },
    {
      title: "设备ID",
      dataIndex: "orderInformation",
      render: (val) => {
        return val.nvrSerialNumber;
      },
    },
    {
      title: "付款时间",
      dataIndex: "notifyTime",
      sorter: {
        compare: (a, b) =>
          new Date(a.notifyTime).getTime() - new Date(b.notifyTime).getTime(),
      },
    },
    {
      title: "授权开始时间",
      dataIndex: "orderInformation",
      render: (val) => {
        return moment(val.nvrStartTime).format("YYYY-MM-DD HH:mm:ss");
      },
      sorter: {
        compare: (a, b) =>
          new Date(a.orderInformation.nvrStartTime).getTime() -
          new Date(b.orderInformation.nvrStartTime).getTime(),
      },
    },
    {
      title: "授权结束时间",
      dataIndex: "orderInformation",
      render: (val) => {
        return moment(val.nvrEndTime).format("YYYY-MM-DD HH:mm:ss");
      },
      sorter: {
        compare: (a, b) =>
          new Date(a.orderInformation.nvrEndTime).getTime() -
          new Date(b.orderInformation.nvrEndTime).getTime(),
      },
    },
    {
      title: "支付金额",
      dataIndex: "buyerPayAmount",
      render: (val) => {
        return `￥${val}`;
      },
      sorter: {
        compare: (a, b) => a.buyerPayAmount - b.buyerPayAmount,
      },
    },
    {
      title: "订单金额",
      dataIndex: "orderInformation",
      render: (val) => {
        return `￥${val.orderSettleAccounts}`;
      },
      sorter: {
        compare: (a, b) =>
          a.orderInformation.orderSettleAccounts -
          b.orderInformation.orderSettleAccounts,
      },
    },
  ];

  return (
    <>
      <div className="top">
        <div className="top-left">
          <div>
            订单号：
            <Input
              maxLength={30}
              style={{ width: inputWidth }}
              placeholder="需输入订单号的全部"
              allowClear
              onChange={(e) => {
                timers && clearTimeout(timers);
                timers = setTimeout(() => {
                  e.target.value
                    ? setSerchData({
                        ...serchData,
                        tradeNo: e.target.value,
                        page: 1,
                      })
                    : (() => {
                        delete serchData["tradeNo"];
                        setSerchData({
                          ...serchData,
                          page: 1,
                        });
                      })();
                }, 800);
              }}
            />
            <br />
            <br />
            设备ID：
            <Input
              placeholder="请输入设备ID"
              allowClear
              defaultValue={nvrId}
              maxLength={10}
              style={{ width: inputWidth }}
              onChange={(e) => {
                timers && clearTimeout(timers);
                timers = setTimeout(() => {
                  setSerchData({
                    ...serchData,
                    nvrSerialnumber: e.target.value,
                    page: 1,
                  });
                  !e.target.value && (nvrId = null);
                }, 800);
              }}
            />
          </div>
          <div>
            支付时间：
            <RangePicker
              style={{ width: inputWidth }}
              format="YYYY/MM/DD HH:mm"
              disabledDate={disabledDate}
              onChange={(time) => {
                time == null &&
                  setSerchData({
                    ...serchData,
                    orderCreationStartTime: "",
                    orderCreationEndTime: "",
                    page: 1,
                  });
              }}
              showTime={
                ({ format: "HH:mm" },
                {
                  defaultValue: [
                    moment("00:00:00", "HH:mm:ss"),
                    moment("23:59:59", "HH:mm:ss"),
                  ],
                })
              }
              onOk={(time) => {
                if (time[0] != null && time[1] !== null) {
                  setSerchData({
                    ...serchData,
                    orderCreationStartTime: moment(time[0]).format(
                      "YYYY-MM-DD HH:mm:ss"
                    ),
                    orderCreationEndTime: moment(time[1]).format(
                      "YYYY-MM-DD HH:mm:ss"
                    ),
                    page: 1,
                  });
                }
              }}
            />
            <br />
            <br />
            授权时间：
            <RangePicker
              style={{ width: inputWidth }}
              format="YYYY/MM/DD HH:mm"
              disabledDate={disabledDate}
              onChange={(time) => {
                time == null &&
                  setSerchData({
                    ...serchData,
                    orderStartTime: "",
                    orderEndTime: "",
                    page: 1,
                  });
              }}
              showTime={
                ({ format: "HH:mm" },
                {
                  defaultValue: [
                    moment("00:00:00", "HH:mm:ss"),
                    moment("23:59:59", "HH:mm:ss"),
                  ],
                })
              }
              onOk={(time) => {
                if (time[0] != null && time[1] !== null) {
                  setSerchData({
                    ...serchData,
                    orderStartTime: moment(time[0]).format(
                      "YYYY-MM-DD HH:mm:ss"
                    ),
                    orderEndTime: moment(time[1]).format("YYYY-MM-DD HH:mm:ss"),
                    page: 1,
                  });
                }
              }}
            />
          </div>
          {/* <div>
            设备类型：
            <Select
              defaultValue="全部"
              style={{ width: inputWidth }}
              onChange={eqTypeChange}
            >
              <Option value="">全部</Option>
              <Option value="1">ULINK发射机</Option>
              <Option value="2">ULINK接收机</Option>
            </Select>
            <br />
            <br />
    
          </div> */}
        </div>
        <div className="top-right">
          {/* <Button size="small" type="primary">
            查询
          </Button> */}
          <Button size="large" type="primary" onClick={downloadExcel}>
            导出数据
          </Button>
        </div>
      </div>

      <Table
        style={{ marginTop: "25px" }}
        columns={columns}
        dataSource={oderData}
        rowKey={(record) => record.tradeNo}
        pagination={{
          onChange: (page, limit) => {
            setSerchData({
              ...serchData,
              page,
              limit,
            });
          },
          pageSizeOptions: [30, 80, 120, 190, 300],
          showTotal: (total) => `共 ${total} 条 `,
          current: serchData.page,
          position: ["bottomCenter"],
          defaultPageSize: 11,
          total: total, //总条数
        }}
      />
    </>
  );
};

export default Order;
